import React from 'react'
import { BaseListPage, IBaseListPageState, IBaseListPageProps, UdDateRangePicker, http, UdModal, uaaApp, IListQueryParams, columnRenders } from '@/lib';
import { Badge, Select, Button, Modal, message, Upload } from 'antd';
import ModelContent from '../TransferDetail/ModelContent';
import apis from '@/apis/AboutQuota';
import udMainStore from '@/store/UdMain';
import '../QuotaAdjustment/Secondary/comm.css'
import { downBlobFile, blobToObject } from '@/utils/methods';
import GmApproval from '../../GmApproval';
import moment from 'moment';


const { Option } = Select
const Modifyexport = 'quota_employee_manager_quotaModifyexport' //导出
const Modifyimport = 'quota_employee_manager_quotaModifyimport' // 导入
const Modifyput = 'quota_employee_manager_quotaModifyput' //调整配额
const checkget = 'quota_employee_manager_changeput' // 配额转移
const OrderTooAli = 'quota_employee_manager_getAssociatedOrderTooAli' //关联订单

enum EDealerType {
  DEALER = '经销商',
  DISTRIBUTOR = '分销商',
}

const statusEnum = {
  '1': '已过期',
  '2': '可使用',
  '3': '未生效',
}

export default class QuotaTransferList extends BaseListPage<QuotaTransferListProps, QuotaTransferListState>{

  // 隐藏掉头曲二曲
  public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  public brandCompanies = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  child: any;
  modal: any;

  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      time: '',
      recordData: '',
      uploading: false,
      selectList: [],
      brandCode: this.brandCompanies[0]?.value,
      brandCompanies: [],
      title: "配额调整转移",
      rowKey: 'id',
      queryApi: apis.QuotaAdjustmentList,
      method: 'GET',
      conditions: [
        {
          id: 'brandCode', label: '销售组织', initialValue: this.brandCompanies[0]?.value, render: () => (
            <Select placeholder="请选择销售组织" onChange={this.handelselect} allowClear={false} >
              {this.brandCompanies.map(({ value, title }) => (<Option key={value} value={value} >{title}</Option>))}
            </Select>
          )
        },
        { id: 'dealerName', label: '客户名称' },
        { id: 'groupName', label: '物料分类名称' },
        {
          id: 'status', label: '状态', render: () => {
            return (
              <Select>
                <Option value="2">可使用</Option>
                <Option value="1">已过期</Option>
                <Option value="3">未生效</Option>
              </Select>
            )
          }
        },
        { id: ['quotaStartTime', 'quotaEndTime'], label: '有效期', render: () => <UdDateRangePicker /> },
      ],
      columns: [
        { title: '序号', key: 'id', dataIndex: 'id', minWidth: '20px', render: (text, reode, index) => index + 1 },
        ['销售组织', 'brandName', null, { minWidth: '60px' }],
        ['客户名称', 'dealerName', null, { minWidth: '140px' }],
        ['客户类型', 'dealerType', columnRenders.enum(EDealerType), { minWidth: '70px' }],
        ['物料分类名称', 'groupName', null, { minWidth: '120px' }],
        ['配额数量/件', 'quotaNum', null, { minWidth: '70px' }],
        ['已使用/件', 'quotaUseNum', null, { minWidth: '50px' }],
        ['可用/件', 'quotaCanNum', null, { minWidth: '40px' }],
        { title: '开始日期', key: 'quotaStartTime', dataIndex: 'quotaStartTime', minWidth: '70px', render: text => text && moment(text).format('YYYY-MM-DD') },
        { title: '结束日期', key: 'quotaEndTime', dataIndex: 'quotaEndTime', minWidth: '70px', render: text => text && moment(text).format('YYYY-MM-DD') },
        {
          title: '状态', key: 'status', dataIndex: 'status', minWidth: '60px', render: (text: number) => (
            <Badge
              status={text == 2 ? 'success' : 'default'}
              text={statusEnum[text]}
            />)
        },
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '120px',
          fixed: 'right',
          render: (text, record) => {
            return (
              <>
                {(uaaApp.canUse(checkget)) && record.status === 2 && <span onClick={() => { this.openModelEdite(record) }} ><a>配额转移</a></span>}
                {uaaApp.canUse(OrderTooAli) && <span className="pad-left" onClick={() => { this.handelnextpage(record) }}><a>关联订单</a></span>}
              </>
            )
          }
        }
      ],
      leftBtns: [
        () => uaaApp.canUse(Modifyexport) && <Button type="primary" onClick={this.handleExport} >导出</Button>,
        () => uaaApp.canUse(Modifyput) && <Button type="primary" onClick={this.handelAdjust}>调整配额</Button>
      ],
      tableProps: {
        scroll: { x: true },
        rowSelection: {
          // getCheckboxProps: this.getCheckboxProps
        }
      }
    }

  }
  private handelselect = (value) => {  //获取销售组织编码
    this.setState({ brandCode: value })
  }
  render() {
    return (
      <>
        {super.render()}
        <Modal
          title="配额转移"
          visible={this.state.visible}
          width={600}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <ModelContent
            time={this.state.time}
            recordData={this.state.recordData}
            selectList={this.state.selectList}
            handleOk={this.handleOk.bind(this)}
            onRef={this.onRef}
          />
        </Modal>
        <GmApproval />
      </>
    )
  }

  private onRef = (ref) => {
    this.child = ref
  }
  private handleSend = () => {//导入
    this.modal = UdModal.open({
      title: '批量导入',
      width: 300,
      content: <>
        <div className='import-user-modal'>
          <Button type='primary' onClick={this.downloadTpl}>下载模板</Button>
          <Upload showUploadList={false} customRequest={this.importUser}><Button type='primary'>导入配额</Button></Upload>
        </div>
      </>,
      footer: null,
      maskClosable: false,
      centered: true,
    })
  }
  private importUser = (option) => { //导入
    this.modal && this.modal.destroy()
    this.setState({ uploading: true })
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    http.post(apis.QuotaModifyImport, formData).then(res => {
      message.success('上传成功')
      this.query()
    }).finally(() => this.setState({ uploading: false }))
  }
  private downloadTpl = () => { //下载模板
    http.post(apis.quotaTransmitImport, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '配额调整')
      }
    })
  }
  // private getCheckboxProps = (record) =>{
  //   return {
  //       disabled: record.status == '1',
  //     }
  // }
  // filterReset = () =>{
  //   this.setState({dataSource:[]})
  // }
  //   handleSearch = (values) =>{
  //     const isBlank = Object.keys(values).length < 1
  //    if(!isBlank){
  //     let p: Partial<IListQueryParams> = {
  //       conditions: values,
  //       v: new Date().getTime()
  //     }
  //     if (this.state.pagination) {
  //       p.page = 1
  //     }
  //     this.handleParamsChange<IListQueryParams>(p)
  //    }else{
  //      message.warning('请选你的筛选条件！')
  //    }
  //  }
  private handelnextpage = (record) => {
    console.log(record);
    // this.props.history.push(`/quota/quotatransfer/detail/${record.brandCode}/${record.dealerCode}/${record.productGroupId}/${record.groupName}/${record.quotaUseNum}`)
    this.props.history.push(`/quota/quotatransfer/detail/${record.id}`)
  }
  private openModelEdite = (record) => {
    this.setState({
      visible: true,
      time: record.quotaStartTime + '至' + record.quotaEndTime,
      recordData: record,
    })
  }
  private handleOk = e => { // 打开model框
    let visible = this.child.changeVal() == undefined ? false : true
    this.setState({ visible });
  };

  private handleCancel = e => { // 关闭model框
    this.setState({
      visible: false,
    });
    this.child.handleCancel()
  };

  private handleExport = () => {

    this.downloadExcel(apis.quotaModifyexport, { quotaRespVos: this.state.selectedRows, brandCode: this.state.brandCode }, '配额调整列表')
  }

  private downloadExcel = (url, params, fileName) => {
    if (this.state.selectedRows.length != 0) {
      http.post(url, params, { responseType: 'arraybuffer' }).then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, fileName)
        }
      })
    } else {
      message.warning('请选择要导出的内容！')
    }

  }

  private handelAdjust = () => { //调整配额
    const { selectedRows } = this.state;

    if (selectedRows.length == 0) {
      message.warning('请选择要调整的内容')
    } else {
      if (selectedRows.some((a: any) => a.status !== 2)) return message.warning('仅可使用状态的配额才能调整')

      // 储存原始 配额数量 和 可用数量 ，在调整的时候用来计算当前的实际可用数量
      const formatSelectRows = selectedRows.map(item => ({ ...item, originQuotaNum: item.quotaNum, originQuotaCanNum: item.quotaCanNum }))
      let data = JSON.stringify(formatSelectRows)
      sessionStorage.setItem('checkTable', data)
      this.props.history.push(`/quota/quotatransfer/secondary/${selectedRows[0].brandCode}`)
    }
  }
}

interface QuotaTransferListState extends IBaseListPageState {
  visible: boolean
  time: any,
  brandCompanies: any
  recordData: any
  selectList: any
  uploading: boolean
  brandCode: any
}

interface QuotaTransferListProps extends IBaseListPageProps {

}